<template>
	<view class="step-item">
		<view class="form-container">
			<view class="form-item">
				<view class="label">活动名称</view>
				<u-input v-model="formData.name" placeholder="篮球宝贝足球队" />
			</view>

			<view class="form-item">
				<view class="label">活动类型</view>
				<view class="cell-wrapper">
					<u-cell-group :border="false">
						<u-cell-item :title="activityType || '请选择'" :arrow="true" arrow-direction="right"
							@click="showActionSheet"></u-cell-item>
					</u-cell-group>
				</view>
			</view>

			<view class="form-item">
				<view class="label">适用年龄</view>
				<view class="age-range">
					<u-input v-model="formData.min_age" type="number" placeholder="最小年龄" :border="true" :clearable="true" />
					<text class="separator">-</text>
					<u-input v-model="formData.max_age" type="number" placeholder="最大年龄" :border="true" :clearable="true" />
				</view>
			</view>

			<view class="form-item">
				<view class="label">报名人数限制</view>
				<view class="number-range">
					<u-input v-model="formData.min_participants" type="number" placeholder="最小人数" :border="true"
						:clearable="true" />
					<text class="separator">-</text>
					<u-input v-model="formData.max_participants" type="number" placeholder="最大人数" :border="true"
						:clearable="true" />
				</view>
			</view>

			<!-- <view class="form-item">
				<view class="label">活动时长（天/小时）</view>
				<view class="duration">
					<view class="input-wrapper">
						<u-input v-model="formData.days" type="number" placeholder="请输入" :border="true" :clearable="true" />
						<text class="unit-text">天</text>
					</view>
					<text class="separator">-</text>
					<view class="input-wrapper">
						<u-input v-model="formData.hours" type="number" placeholder="请输入" :border="true" :clearable="true" />
						<text class="unit-text">时</text>
					</view>
				</view>
			</view> -->

			<view class="form-item">
				<view class="label">活动开始时间</view>
				<view class="input-with-icon" @tap="chooseStartTime">
					<view class="inputview" :style="{ color: formData.start_time_text ? '#000' : 'rgb(192, 196, 204)' }">
						{{formData.start_time_text || "请选择开始时间"}}
					</view>
					<!-- <u-input :disabled="true" v-model="formData.start_time_text" placeholder="请选择开始时间" :border="true" :clearable="false" /> -->
					<u-icon class="suffix-icon" name="calendar" size="28"></u-icon>
				</view>
			</view>

			<view class="form-item">
				<view class="label">活动截止时间</view>
				<view class="input-with-icon" @click="showEndTimePicker=true">
					<view class="inputview" :style="{ color: formData.end_time_text ? '#000' : 'rgb(192, 196, 204)' }">
						{{formData.end_time_text || "请选择结束时间"}}
					</view>
					<!-- <u-input :disabled="true" v-model="formData.end_time_text" placeholder="请选择结束时间" :border="true" :clearable="false" /> -->
					<u-icon class="suffix-icon" name="calendar" size="28"></u-icon>
				</view>
			</view>

			<view class="form-item">
				<view class="label">活动地点</view>
				<view class="input-with-icon" @click="toChooseMap">
					<view class="inputview" :style="{ color: formData.address ? '#000' : 'rgb(192, 196, 204)' }">
						<view style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;margin-right: 40rpx;">
							{{formData.address || "请选择地址"}}
						</view>
						<u-icon class="suffix-icon" style="color:#000" name="map-fill" size="28"></u-icon>
					</view>
					<!-- <u-input @click="showMap = true" v-model="formData.address" placeholder="请选择" :border="true" :clearable="false" /> -->
				</view>
			</view>

			<view class="form-item">
				<view class="label">活动简介</view>
				<view class="description-wrapper">
					<u-input type="textarea" v-model="formData.description" placeholder="请输入" />
				</view>
			</view>

			<view class="form-item">
				<view class="label">活动封面图片</view>
				<u-upload :action="uploadUrl" width="190" height="190" :file-list="fileList" :header="uploadHeaders"
					@on-success="afterRead" @on-remove="deletePic" :max-count="5" accept="image/*,video/*" />
			</view>

			<view class="bottom-buttons">
				<view class="cancel-btn" @click="cancel">
					<text>取消</text>
				</view>
				<view class="save-btn" @click="save">
					<text>保存</text>
				</view>
			</view>
		</view>
		<!-- #ifdef H5 -->
		<u-popup mode="right" width="100%" height="100%" v-model="showMap" @open="openMap">
			<map-selector ref="mapSelector" @select="handlerSelectMap" @cancel="showMap = false" />
		</u-popup>
		<!-- #endif -->

		<u-picker v-model="showStartTimePicker" mode="time" @confirm="handleStartTimeConfirm"></u-picker>
		<u-picker v-model="showEndTimePicker" mode="time" @confirm="handleEndTimeConfirm"></u-picker>
		<u-action-sheet :list="actionSheetList" v-model="showSheet" @click="selectType"
			:safe-area-inset-bottom="true"></u-action-sheet>
	</view>
</template>

<script>
	import {
		addActivity,
		editActivity,
		trainerList
	} from '@/api/launchevent.js';
	import {
		baseURL
	} from '@/config/app.js'
	import store from 'store';
	import mapSelector from '@/components/map/index.vue';
	import {
		urlencode
	} from '@/utils/tools';
	// 日期格式化函数
	function formatDate({
		year,
		month,
		day,
		timestamp
	}) {
		const date = new Date(timestamp * 1000);
		const hours = date.getHours().toString().padStart(2, '0');
		const minutes = date.getMinutes().toString().padStart(2, '0');
		const seconds = date.getSeconds().toString().padStart(2, '0');
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}
	export default {
		components: {
			mapSelector,
		},
		props: {
			activityId: {
				type: [Number, String],
				default: null
			},
			initData: {
				type: Object,
				default: {}
			}
		},
		computed: {
			activityType() {
				return this.actionSheetList.find(item => item.value === this.formData.type)?.text || '';
			}
		},
		data() {
			return {
				showStartTimePicker: false,
				showEndTimePicker: false,
				showMap: false,
				show: false,
				minDate: '',
				maxDate: '',
				trainerId: '',
				locationData: {},
				formData: {
					name: '',
					type: '',
					min_age: '',
					max_age: '',
					min_participants: '',
					max_participants: '',
					start_time: '',
					end_time: '',
					address: '',
					description: '',
					images: []
				},
				fileList: [],
				showSheet: false,
				calendarShow: false,
				calendarType: '',
				actionSheetList: [{
						text: '冬令营',
						value: 'winter'
					},
					{
						text: '夏令营',
						value: 'summer'
					},
					{
						text: '普通',
						value: 'common'
					},
					{
						text: '公益',
						value: 'welfare'
					}
				],
				uploadUrl: baseURL + '/businessapi/Upload/image',
				uploadHeaders: {
					version: '3.1.0',
					token: store.getters.token,
				},
				defaultDate: '',
				mapUrl: baseURL + '/admin/map',
			};
		},
		methods: {
			chooseStartTime() {
				this.showStartTimePicker = true
			},
			toChooseMap() {
				// #ifdef APP-PLUS
				uni.navigateTo({
					url: `/components/web-view/web-view?url=${encodeURIComponent(this.mapUrl)}`
				});
				// #endif
				// #ifdef H5
				this.showMap = true
				// #endif
			},
			openMap() {
				this.$refs.mapSelector.open();
			},
			closeMap() {
				this.showMap = false;
			},
			handlerSelectMap(data) {
				console.log('选择的位置完整数据:', JSON.stringify(data));
				
				// 处理可能的嵌套数据结构（如来自postMessage的数据）
				let locationData = data;
				if (data.data && data.data.type === 'locationSelected' && data.data.location) {
					locationData = data.data.location;
					console.log('从postMessage中提取location数据:', locationData);
				} else if (data.location && typeof data.location === 'object') {
					console.log('直接使用data中的location数据');
				}
				
				// 确保address是字符串
				let addressStr = '';
				if (typeof locationData.address === 'string') {
					addressStr = locationData.address;
				} else if (typeof locationData.address === 'object' && locationData.address) {
					addressStr = locationData.address.name || '';
				}
				
				this.formData.address = addressStr;
				
				// 获取省市区ID并进行有效性检查
				let provinceId = 0;
				let cityId = 0;
				let districtId = 0;
				
				try {
					// 尝试直接转换
					if (locationData.provinceCode) {
						provinceId = Number(locationData.provinceCode) || 0;
					}
					if (locationData.cityCode) {
						cityId = Number(locationData.cityCode) || 0;
					}
					if (locationData.districtCode) {
						districtId = Number(locationData.districtCode) || 0;
					}
					
					// 临时解决方案：如果在长沙，使用固定的ID
					if (locationData.province && locationData.province.includes('湖南') || 
					    locationData.city && locationData.city.includes('长沙')) {
						provinceId = 430000;
						cityId = 430100;
					}
					
					console.log('解析后的省市区ID:', provinceId, cityId, districtId);
				} catch (e) {
					console.error('转换省市区ID失败:', e);
				}
				
				this.formData.province_id = provinceId;
				this.formData.city_id = cityId;
				this.formData.district_id = districtId;
				
				// 提取经纬度 - 尝试从多个可能的位置提取
				let longitude = '';
				let latitude = '';
				
				// 1. 从location对象提取
				if (locationData.location && typeof locationData.location === 'object') {
					if (locationData.location.lng && locationData.location.lat) {
						longitude = locationData.location.lng;
						latitude = locationData.location.lat;
						console.log('从location对象提取经纬度:', {lng: longitude, lat: latitude});
					}
				}
				
				// 2. 从根对象提取
				if (!longitude && !latitude && locationData.lng && locationData.lat) {
					longitude = locationData.lng;
					latitude = locationData.lat;
					console.log('从根对象提取经纬度:', {lng: longitude, lat: latitude});
				}
				
				// 3. 从position.point对象提取
				if (!longitude && !latitude && 
					locationData.position && 
					locationData.position.point) {
					longitude = locationData.position.point.longitude;
					latitude = locationData.position.point.latitude;
					console.log('从position.point对象提取经纬度:', {lng: longitude, lat: latitude});
				}
				
				// 4. 从location.position.point对象提取
				if (!longitude && !latitude && 
					locationData.location && 
					locationData.location.position && 
					locationData.location.position.point) {
					longitude = locationData.location.position.point.longitude;
					latitude = locationData.location.position.point.latitude;
					console.log('从location.position.point对象提取经纬度:', {lng: longitude, lat: latitude});
				}
				
				this.formData.longitude = longitude;
				this.formData.latitude = latitude;
				
				this.$set(this.formData, 'location', addressStr);
				
				console.log('设置后的表单数据:', JSON.stringify({
					address: this.formData.address,
					province_id: this.formData.province_id,
					city_id: this.formData.city_id,
					district_id: this.formData.district_id,
					longitude: this.formData.longitude,
					latitude: this.formData.latitude,
					location: this.formData.location
				}));
				
				this.showMap = false;
			},
			showActionSheet() {
				this.showSheet = true;
			},
			selectType(index) {
				this.formData.type = this.actionSheetList[index].value;
				this.showSheet = false;
			},

			afterRead(event) {
				this.formData.images.push(event.data.url);
			},

			deletePic(event) {
				this.formData.images.splice(event, 1);
			},

			validateForm() {
				if (!this.formData.name) {
					this.$u.toast('请输入活动名称');
					return false;
				}
				if (!this.formData.type) {
					this.$u.toast('请选择活动类型');
					return false;
				}
				if (!this.formData.startTime || !this.formData.endTime) {
					this.$u.toast('请选择活动时间');
					return false;
				}
				if (!this.formData.location) {
					this.$u.toast('请选择活动地点');
					return false;
				}
				return true;
			},

			async save() {
				if (this.activityId) {
					await editActivity({
						id: this.activityId,
						...this.formData
					});
				} else {
					const res = await addActivity(this.formData);
					this.$emit('created', res.id); // 通知父组件新创建的ID
				}
				this.$emit('next');
			},

			async trainerList() {
				try {
					const res = await trainerList();
					console.log('trainerList', res.list.data)
					if (res && res.list && res.list.data && res.list.data.length > 0) {
						this.trainerId = res.list.data[0].id;
						console.log('获取到的训练师 id:', this.trainerId);
					} else {
						console.log('未找到有效的训练师数据');
					}
				} catch (error) {
					console.error('获取训练师列表失败:', error);
				}
			},
			cancel() {
				this.$emit('cancel');
			},
			handleStartTimeConfirm(e) {
				this.formData.start_time = formatDate(e);
				this.formData.start_time_text = this.formData.start_time
				this.showStartTimePicker = false;
			},
			handleEndTimeConfirm(e) {
				this.formData.end_time = formatDate(e);
				this.formData.end_time_text = this.formData.end_time
				this.showEndTimePicker = false;
			}
		},

		watch: {
			locationData: {
				handler(newVal) {
					if (newVal && newVal.address) {
						this.formData.location = newVal.address;
					}
				},
				deep: true,
				immediate: true
			},
			initData: {
				handler(newVal) {
					let keys = ['name', 'max_age', 'min_age', 'max_participants', 'min_participants', 'start_time',
						'start_time_text', 'end_time', 'end_time_text', 'address', 'description'
					];
					let pick = {}
					for (const key of keys) {
						pick[key] = newVal[key]
					}
					this.formData = {
						...this.formData,
						...pick
					}
					console.log('initdata', this.formData)
				},
				deep: true,
				immediate: true
			},
		},

		mounted() {
			this.trainerList();
			this.locationData = uni.getStorageSync('locationData');
			// 初始化时也设置一次地址
			if (this.locationData && this.locationData.address) {
				this.formData.location = this.locationData.address;
			}
			uni.$on('locationConfirm', obj => {
				console.log('addressObj', obj)
				this.handlerSelectMap(obj)
			});
		}
	};
</script>

<style lang="scss">
	/* 添加一个不带 scoped 的全局样式块 */
	.u-action-sheet-item__subtext.data-v-5a210273,
	.u-action-sheet-item__subtext.u-line-1.data-v-5a210273 {
		margin-top: 0 !important;
		padding-top: 20rpx !important;
	}
</style>

<style lang="scss" scoped>
	.step-item {
		background-color: #ffffff;
		border-radius: 8rpx;
		padding: 20rpx;
	}

	.launch-event {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.form-container {
		padding: 20rpx;
	}

	.form-item {
		margin-bottom: 30rpx;

		.label {
			font-size: 28rpx;
			color: #000000;
			font-weight: 500;
			margin-bottom: 10rpx;
		}

		/deep/ .u-input {
			margin-top: 8rpx;
		}

		.description-wrapper {
			// width: 686rpx;
			height: 200rpx;
			background: #ffffff;
			border-radius: 8rpx;
			border: 1rpx solid #d5d5d5;
			padding: 20rpx;
		}
	}

	.age-range,
	.number-range,
	.duration {
		display: flex;
		align-items: center;

		.separator {
			padding: 0 20rpx;
		}

		/deep/ .u-input {
			flex: 1;

			&__content {
				padding: 10rpx;
				background-color: #ffffff;
				border: 1px solid #dcdfe6;
				border-radius: 4px;
			}
		}
	}

	.bottom-buttons {
		display: flex;
		justify-content: center;
		gap: 24rpx;
		padding: 40rpx 20rpx;

		.cancel-btn {
			width: 331rpx;
			height: 90rpx;
			background: #fcfffe;
			border-radius: 44rpx;
			border: 2rpx solid #d5d5d5;
			display: flex;
			align-items: center;
			justify-content: center;

			text {
				font-size: 32rpx;
				color: #333;
			}
		}

		.save-btn {
			width: 331rpx;
			height: 90rpx;
			background: #0dc160;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			text {
				font-size: 32rpx;
				color: #ffffff;
			}
		}
	}

	.cell-wrapper {
		/deep/ .u-cell {
			padding: 0;

			&-group {
				margin: 0;
			}

			&-item {
				padding-left: 0;

				&__body {
					padding: 10rpx 0;
				}
			}
		}
	}

	.duration {
		.input-wrapper {
			flex: 1;
			position: relative;

			.unit-text {
				position: absolute;
				right: 10rpx;
				top: 50%;
				transform: translateY(-50%);
				color: #666;
			}

			/deep/ .u-input__input {
				padding-right: 40rpx;
			}
		}
	}

	.input-with-icon {
		position: relative;

		.suffix-icon {
			position: absolute;
			right: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			z-index: 1;
		}

		/deep/ .u-input {
			&__input {
				padding-right: 60rpx;
			}
		}
	}

	.inputview {
		border-radius: 6rpx;
		border-radius: 4px;
		border: 1px solid rgb(220, 223, 230);
		font-size: 28rpx;
		min-height: 36px;
		padding: 0px 10px;
		margin-top: 4px;
		text-align: left;
		color: rgb(192, 196, 204);
		display: flex;
		align-items: center;
	}
</style>